#include "libc/stdint.h"
#include "driver/pl031/time.h"


const char Days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const uint32_t mon_yday[2][12] = {
	{0,31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334},
	{0,31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335},
};

// 时间戳转年月日时分秒
void bbt_localtime(time *time, uint32_t time_s)
{
	uint32_t Pass4year = 0;
	int hours_per_year = 0;

	//取秒时间
	time->second=(int)(time_s % 60);
	time_s /= 60;

	//取分钟时间
	time->minute=(int)(time_s % 60);
	time_s /= 60;

    time_s += 8;  // 加上8小时时差

	//取过去多少个四年，每四年有 1461*24 小时
	Pass4year = time_s / (1461L * 24L);
	//计算年份
	time->year = (Pass4year << 2) + 1970;
	//四年中剩下的小时数
	time_s %= 1461L * 24L;
	//校正闰年影响的年份，计算一年中剩下的小时数
	while(1)
	{
		//一年的小时数
		hours_per_year = 365 * 24;
		//判断闰年，是闰年，一年则多24小时，即一天
		if ((time->year & 3) == 0) hours_per_year += 24;

		if (time_s < hours_per_year) break;

		time->year++;
		time_s -= hours_per_year;
	}
	//小时数
	time->hour=(int)(time_s % 24);
	//一年中剩下的天数
	time_s /= 24;
	//假定为闰年
	time_s++;
	//校正闰年的误差，计算月份，日期
	if((time->year & 3) == 0) {
		if (time_s > 60) {
			time_s--;
		} else {
			if (time_s == 60) {
				time->month = 1;
				time->day = 29;
				return ;
			}
		}
	}
	//计算月日
	for (time->month = 0; Days[time->month] < time_s; time->month++)
	{
		time_s -= Days[time->month];
	}
    time->month++; // 数组从零开始， 所以月份+1

	time->day = (int)(time_s);

	return;
}

